<template>
  <div class="box">
    <div class="box-content">
      <div class="search">
        <div class="search-btn">
          <a-button
            v-if="onAccurateBtn"
            type="primary"
            :loading="btnLoading"
            :disabled="!hasSelected"
            @click="goDistribution"
            >一键分配</a-button
          >
          <button v-else class="no-accurate" :disabled="!hasSelected">精确分配</button>
          <a-button
            type="primary"
            style="margin: 0 0 0 16px"
            ghost
            :disabled="!hasSelected"
            :loading="btnLoading"
            @click="preciseDistribution"
            >精确分配</a-button
          >
          <!-- <a-button type="primary" style="margin: 0 0 0 16px" ghost @click="consoleLog">
            打印信息
          </a-button> -->
        </div>
      </div>
      <div class="bottom-content">
        <div class="bottom-content-left">
          <a-tree
            v-model:expandedKeys="expandedKeys"
            v-model:selectedKeys="selectedKeys"
            v-model:checkedKeys="checkedKeys"
            checkable
            :tree-data="treeData"
            :field-names="{ children: 'childrenClass', title: 'className' }"
            @check="checkTree"
          />
        </div>
        <div class="bottom-content-center">
          <a-tabs @tabClick="tabClick">
            <a-tab-pane
              :key="sexChoice[0].dataIndex"
              :tab="sexChoice[0].title + ' (' + sexChoice[0].data.length + ')'"
            >
              <!-- 搜索 -->
              <Col :span="10">
                <a-input
                  v-model:value="searchValueGirl"
                  autocomplete="off"
                  placeholder="请输入您的搜索内容"
                  maxlength="30"
                  @keyup.enter="onSearch(searchValueGirl, sexChoice[0].dataIndex)"
                >
                  <template #prefix
                    ><img src="@/assets/images/accommodation/jiaoxue_icon_sousuo.png" alt=""
                  /></template>
                </a-input>
              </Col>
              <!-- 宿舍楼列表 -->
              <div style="padding: 0 10px">
                <a-menu
                  v-model:selectedKeys="selectedKeys"
                  mode="inline"
                  style="width: 99%"
                  :open-keys="openKeys"
                  @openChange="onOpenChange"
                >
                  <a-sub-menu v-for="(item, index) in dormitoryListGirl" :key="index + item.name">
                    <template #title> {{ item.name }} </template>
                    <a-sub-menu
                      v-for="(elem, key) in item.storeyList"
                      :key="`${index}-${key}`"
                      :disabled="item.existStoreyList?.indexOf(elem.id) === -1"
                      :title="`${elem.id}楼`"
                      @titleClick="onTotal(item.id, elem.id, index, key, 'girl')"
                    >
                      <template
                        v-if="item.existStoreyList?.indexOf(elem.id) === -1"
                        #expandIcon
                      ></template>
                      <div style="padding: 0 0 10px 80px">
                        <div class="checkBox">
                          <!-- <Row :gutter="[4, 8]"> -->
                          <li v-for="(room, i) in elem.roomList" :key="i" :span="12">
                            <div style="display: flex">
                              <a-checkbox
                                v-model:checked="room.checked"
                                :disabled="!room.checked && !sexChoice[0].data.length"
                                class="deta-checked"
                                @change="checkboxChangeGirl(room, room.checked)"
                              />
                              <Tooltip
                                :overlay-style="{ whiteSpace: 'normal' }"
                                :get-popup-container="
                                  triggerNode => {
                                    return triggerNode.parentNode || document.body;
                                  }
                                "
                                placement="topLeft"
                                :title="room.name + `${'宿舍'}`"
                              >
                                <p
                                  style="
                                    width: 70px;
                                    white-space: nowrap;
                                    overflow: hidden;
                                    text-overflow: ellipsis;
                                    margin-left: 8px;
                                  "
                                  >{{ room.name }}宿舍</p
                                >
                              </Tooltip>
                              {{ room.bedNum }}人间
                              <span v-if="room.airBedNumber !== 0" style="margin-left: 8px"
                                >{{ room.airBedNumber }}空床
                              </span>
                            </div>
                          </li>
                          <!-- </Row> -->
                        </div>
                      </div>
                    </a-sub-menu>
                  </a-sub-menu>
                </a-menu>
              </div>
            </a-tab-pane>
            <a-tab-pane
              :key="sexChoice[1].dataIndex"
              :tab="sexChoice[1].title + ' (' + sexChoice[1].data.length + ')'"
            >
              <!-- 搜索 -->
              <Col :span="10">
                <a-input
                  v-model:value="searchValue"
                  autocomplete="off"
                  placeholder="请输入您的搜索内容"
                  @keyup.enter="onSearch(searchValue, sexChoice[1].dataIndex)"
                >
                  <template #prefix
                    ><img src="@/assets/images/accommodation/jiaoxue_icon_sousuo.png" alt=""
                  /></template>
                </a-input>
              </Col>
              <div style="padding: 0 10px; overflow: auto; max-height: 600px">
                <a-menu
                  v-model:selectedKeys="selectedKeys"
                  mode="inline"
                  style="width: 99%"
                  :open-keys="openKeys"
                  @openChange="onOpenChange"
                >
                  <a-sub-menu v-for="(item, index) in dormitoryListBoy" :key="index">
                    <template #title> {{ item.name }} </template>
                    <a-sub-menu
                      v-for="(elem, key) in item.storeyList"
                      :key="`${index}-${key}`"
                      :disabled="item.existStoreyList?.indexOf(elem.id) === -1"
                      :title="`${elem.id}楼`"
                      @titleClick="onTotal(item.id, elem.id, index, key, 'boy')"
                    >
                      <template
                        v-if="item.existStoreyList?.indexOf(elem.id) === -1"
                        #expandIcon
                      ></template>
                      <div style="padding: 0 0 10px 80px">
                        <div class="checkBox">
                          <!-- <Row :gutter="[4, 8]"> -->
                          <li v-for="(room, i) in elem.roomList" :key="i" :span="12">
                            <div
                              style="display: flex"
                              :class="{ 'room-box-checked': room.checked }"
                            >
                              <a-checkbox
                                v-model:checked="room.checked"
                                :disabled="!room.checked && !sexChoice[1].data.length"
                                class="deta-checked"
                                @change="checkboxChangeBoy(room, room.checked)"
                              />
                              <Tooltip
                                :overlay-style="{ whiteSpace: 'normal' }"
                                :get-popup-container="
                                  triggerNode => {
                                    return triggerNode.parentNode || document.body;
                                  }
                                "
                                placement="topLeft"
                                :title="room.name + `${'宿舍'}`"
                              >
                                <p
                                  style="
                                    width: 70px;
                                    white-space: nowrap;
                                    overflow: hidden;
                                    text-overflow: ellipsis;
                                    margin-left: 8px;
                                  "
                                  >{{ room.name }}宿舍</p
                                >
                              </Tooltip>
                              {{ room.bedNum }}人间
                              <span v-if="room.airBedNumber !== 0" style="margin-left: 8px">
                                {{ room.airBedNumber }}空床
                              </span>
                            </div>
                          </li>
                          <!-- </Row> -->
                        </div>
                      </div>
                    </a-sub-menu>
                  </a-sub-menu>
                </a-menu>
              </div>
            </a-tab-pane>
          </a-tabs>
        </div>
        <div class="bottom-content-right">
          <div class="allocation-details-title">分配详情</div>
          <div v-for="item in allocationDetailsList" :key="item.id">
            <div class="class-name">{{ item.className }}</div>
            <div v-for="ites in item.list" :key="ites.id">
              <div class="info">
                <p>{{ ites.gender }}</p>
                <p>
                  <span style="color: #fe8f8f; margin-right: 24px"
                    >未分配: {{ ites.noDistribution.length }}</span
                  ><span>预分配: {{ ites.distribution.length }}</span>
                </p>
              </div>
              <div class="info-content">
                <div v-for="items in ites.data" :key="items.id" class="details">
                  <div>{{ items.name }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 宿舍精准分配 提示弹框 -->
    <my-dialog
      :dialog-state="dormitoryAllocation.visible"
      :dialog-title="dormitoryAllocation.title"
      :dialog-width="dormitoryAllocation.width"
      :btn-state="dormitoryAllocation.btnState"
      :icon-type="dormitoryAllocation.iconType"
      :btn-loading="btnLoading"
      @handleCancel="dormitoryCancel()"
      @handleOk="dormitoryTip(dormitoryAllocation.state)"
    >
      <template v-slot:location>
        <div class="checkOutStyle">
          <img src="@/assets/images/accommodation/drawable-xxxhdpi_popu_icon_warn.png" alt="" />
          <span> {{ text }}</span>
        </div>
        <!-- <p class="checkOut-notes">注：此动作将会清除已选内容所有住宿信息，请谨慎操作。</p> -->
      </template>
    </my-dialog>
    <!-- 宿舍精准分配 弹框 -->
    <my-dialog
      :dialog-state="dormitoryPrecise.visible"
      :dialog-title="dormitoryPrecise.title"
      :btn-state="dormitoryPrecise.state"
      :dialog-width="dormitoryPrecise.width"
      :icon-type="dormitoryPrecise.iconType"
      :btn-loading="btnLoading"
      @handleCancel="handleCancel()"
      @handleOk="handleOk()"
    >
      <template v-slot:location>
        <div class="campus">高一1班</div>
        <div class="content">
          <div class="option">
            <a-tabs default-active-key="1">
              <a-tab-pane v-for="item in sexChoice" :key="item.dataIndex" :tab="item.title">
                <a-tree :tree-data="treeDatass" />
              </a-tab-pane>
            </a-tabs>
          </div>
          <div class="detailsStudent">
            <div class="info">详情</div>
            <div class="info-content">
              <a-checkbox-group>
                <Row>
                  <Col :span="8" class="flex" style="margin-right: 38px; line-height: 32px">
                    <a-checkbox value="A"> A </a-checkbox>
                    <div class="flex" style="align-items: center">
                      <img
                        src="@/assets/images/accommodation/drawable-xxxhdpi_home_menu_icon_zhusu.png"
                        alt=""
                        style="width: 32px; height: 32px; border-radius: 50%"
                      />
                      <div>姓名</div>
                    </div>
                  </Col>
                </Row>
              </a-checkbox-group>
            </div>
          </div>
        </div>
      </template>
    </my-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, watch, computed } from 'vue';
import { Row, Col, Message, Tooltip } from 'ant-design-vue';
import { debounce } from '@/utils/debounce.js';
import {
  getClassInfo,
  getDormitorySexList,
  getDormitoryRoom,
  getDormitoryRoomaNameList,
  automaticAssignDormitory,
  getUnAllocationClassStudentId,
  getStudentDistributionList,
  getRoomDetails
} from '@/api/classManage';
import MyDialog from '@/components/dialog/index.vue';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();
let classId = ref([]);
let onAccurateBtn = ref(true); // 一键分配按钮状态

const hasSelected = computed(() => checkedKeys.value.length > 0);
/** ****************************** 测试开始 ****************************************** */

const consoleLog = () => {
  console.log(sexChoice.value, '男生/女生数据(tabs栏)-sexChoice.value');
  console.log(allocationDetailsList.value, '分配详情-allocationDetailsList.value');
  console.log(treeData.value, '年级树-treeData.value');
  console.log(dormitoryListBoy.value, '男生宿舍楼-dormitoryListBoy.value');
  console.log(dormitoryListGirl.value, '女生宿舍楼-dormitoryListGirl.value');
  console.log(studentGirlDataInfo.value, '女生分配信息-studentGirlDataInfo.value');
  console.log(studentBoylDataInfo.value, '男生分配信息-studentBoylDataInfo.value');
};

let paramsClassId = ref([]); // 所有传递过来的班级ID
// 男生/女生数据
const sexChoice = ref([
  {
    title: '女生',
    dataIndex: '0',
    data: [],
    num: ''
  },
  {
    title: '男生',
    dataIndex: '1',
    data: [],
    num: ''
  }
]);
let btnLoading = ref(false);
// watch(route, () => {
//   console.log(route);
//   if (!route.query.id) {
//     router.push('/admin/classInfo');
//   }
// });

// 女生分配信息
const studentGirlDataInfo = ref([]);
// 男生分配信息
const studentBoylDataInfo = ref([]);
// const girlDataLength = computed(() => studentGirlDataInfo.value.length);
// const boyDataLength = computed(() => studentBoylDataInfo.value.length);
// watch(girlDataLength, value => {
//   studentGirlDataInfo.value = studentGirlDataInfo.value.filter(v => v.data.length);
//   studentBoylDataInfo.value = studentBoylDataInfo.value.filter(v => v.data.length);
// });
// watch(boyDataLength, value => {
//   studentBoylDataInfo.value = studentBoylDataInfo.value.filter(v => v.data.length);
// });

onMounted(() => {
  let bodySty = document.getElementById('myApp');
  bodySty.setAttribute('class', 'bodyStyle');
  if (route.query.id) {
    paramsClassId.value = JSON.parse(route.query.id);
    sessionStorage.setItem('idArr', route.query.id);
  } else if (sessionStorage.getItem('idArr')) {
    paramsClassId.value = JSON.parse(sessionStorage.getItem('idArr'));
  } else {
    router.push('/admin/classInfo');
  }
  classId.value = paramsClassId.value.toString();
  // paramsClassId.value.forEach(async items => {
  //   await getClassStudentId(items, JSON.parse(route.query.studentUserId));
  // });
  getClassStudentId('1', JSON.parse(route.query.studentUserId));
  // setTimeout(function () {
  //   getClassList();
  //   getDormitoryList(0);
  //   getDormitoryList(1);
  // }, 100);
});

const getClassStudentId = async (id, studentUserId) => {
  let girlData = [];
  let boyData = [];
  // getStudentDistributionList 新的
  // getUnAllocationClassStudentId 旧的
  console.log('sjbwy', id);
  console.log('sjbwy222', studentUserId);

  await getStudentDistributionList(studentUserId).then(res => {
    let data = res.data.data;
    data.forEach((item, index) => {
      if (item.gender === '女') {
        item.studentList.forEach(elem => {
          girlIdList.value.push(elem);
        });

        girlData = girlData.concat({
          classid: id,
          studentIdList: item.studentList
        });
      } else {
        item.studentList.forEach(elem => {
          boylIdList.value.push(elem);
        });
        boyData = boyData.concat({
          classid: id,
          studentIdList: item.studentList
        });
      }
    });
    sexChoice.value[0].data = girlIdList.value;
    sexChoice.value[0].num = girlIdList.value.length;
    sexChoice.value[1].data = boylIdList.value;
    sexChoice.value[1].num = boylIdList.value.length;
    initialGirl.value = sexChoice.value[0].data;
    initialBoy.value = sexChoice.value[1].data;
    girlDataId.value = girlData;
    boyDataId.value = boyData;
    console.log('第一个执行的函数-getClassStudentId', sexChoice);
    setTimeout(function () {
      getClassList(studentUserId);
      getDormitoryList(0);
      getDormitoryList(1);
    }, 0);
  });
};
// 获取班级列表
const getClassList = async studentUserId => {
  await getClassInfo(studentUserId).then(res => {
    if (res.data.code === 200) {
      let data = [];
      res.data.data.forEach((item, index) => {
        let gradleChild = [];
        item.key = String(index);
        item.className = item.sectionName;
        if (item.gradleList && item.gradleList.length) {
          item.gradleList.forEach((itemGradle, indexGradle) => {
            let child = [];
            itemGradle.key = indexGradle;
            itemGradle.className = itemGradle.gradeName;
            if (itemGradle.childrenClass && itemGradle.childrenClass.length) {
              /* eslint-disable */
              itemGradle.childrenClass.forEach((subItem, subIndex) => {
                if (paramsClassId.value.indexOf(String(subItem.id)) !== -1) {
                  child.push({
                    boyNum: subItem.boyNum,
                    className: subItem.className,
                    girlNum: subItem.girlNum,
                    gradeId: subItem.gradeId,
                    gradeName: subItem.gradeName,
                    key: `${String(itemGradle.gradeId)}-${String(subItem.id)}`,
                    id: subItem.id
                  });
                }
                /* eslint-enable */
              });
              if (child.length) {
                gradleChild.push({
                  gradeId: itemGradle.gradeId,
                  gradeName: itemGradle.gradeName,
                  key: `${String(itemGradle.gradeId)}`,
                  className: itemGradle.gradeName,
                  childrenClass: child
                });
              }
            }
          });
        }
        if (gradleChild.length) {
          data.push({
            sectionCode: item.sectionCode,
            sectionName: item.sectionName,
            key: `${String(item.sectionCode)}`,
            className: item.sectionName,
            childrenClass: gradleChild
          });
        }
      });
      treeData.value = data;
      let id = '';
      /*eslint-disable */
      treeData.value.forEach((itemSection, index) => {
        itemSection.childrenClass.forEach(item => {
          item.childrenClass.forEach((itemChild, i) => {
            id = itemChild.id.toString();
            console.log(item, 'item');
            assignment(id, item, itemChild, itemSection);
          });
        });
      });
      /*eslint -enable */
      console.log('详情入参data', data);
      console.log('详情入参sexChoice.value[0].data', sexChoice.value[0].data);
      console.log('详情入参sexChoice.value[1].data', sexChoice.value[1].data);
      getAllocationDetails(data, sexChoice.value[0].data, sexChoice.value[1].data);
    }
    console.log('第二个执行的函数-getClassList');
  });
};
const assignment = (id, item, itemChild, itemSection) => {
  let classIdArr = classId.value.split(',');
  classIdArr.forEach((i, index) => {
    if (id === i) {
      expandedKeys.value.push(item.key);
      expandedKeys.value.push(itemSection.key);
      checkedKeys.value.push(itemChild.key);
      girlArr.value.push(itemChild.girlNum);
      boyArr.value.push(itemChild.boyNum);
      girlArr.value.forEach(item => {
        girlsNum.value = girlsNum.value + item;
      });
      boyArr.value.forEach(item => {
        boysNum.value = boysNum.value + item;
      });
    }
  });
};
// 女楼层/男楼层点击事件
const onTotal = (dormitoryId, storey, index, key, type) => {
  console.log('楼层点击', type);
  if (type === 'girl') {
    if (!searchValueGirl.value) {
      if (dormitoryListGirl.value[index].storeyList[key].roomList.length === 0) {
        getDormitoryRoom(dormitoryId, storey, genderValue.value).then(res => {
          let data = [];
          let arr = res.data.data.filter(elem => elem.airBedNumber);
          arr.forEach(item => {
            let studentAll = [...studentGirlDataInfo.value, ...studentBoylDataInfo.value];
            console.log(studentAll);
            console.log(item);
            // eslint-disable-next-line max-nested-callbacks
            let ids = studentAll.map(v => v.id);
            if (ids.indexOf(item.id) === -1) {
              data.push({
                checked: false, // 选中状态
                disabled: false, // 是否禁选
                airBedNumber: item.airBedNumber,
                disableNumber: item.disableNumber,
                bedNum: item.bedNum,
                dormitoryId: item.dormitoryId,
                dormitoryName: item.dormitoryName,
                genderAttribute: item.genderAttribute,
                id: item.id,
                lou: item.storey,
                name: item.name,
                occupancyNumber: item.occupancyNumber,
                roomPhone: item.roomPhone,
                schoolId: item.schoolId,
                storey: item.storey,
                tenantId: item.tenantId,
                useState: item.useState,
                data: [],
                bedNumberList: []
              });
            } else {
              // eslint-disable-next-line max-nested-callbacks
              data = [...data, ...studentAll.filter(student => student.id === item.id)];
            }
          });
          data.forEach(v => {
            if (v.data.length) {
              v.checked = true;
            } else {
              v.checked = false;
            }
          });
          dormitoryListGirl.value[index].storeyList[key].roomList = data;
        });
      }
    }
  } else if (type === 'boy') {
    if (!searchValue.value) {
      console.log(!searchValueGirl.value, '!searchValueGirl.value');
      if (dormitoryListBoy.value[index].storeyList[key].roomList.length === 0) {
        getDormitoryRoom(dormitoryId, storey, genderValue.value).then(res => {
          let data = [];
          let arr = res.data.data.filter(elem => elem.airBedNumber);
          arr.forEach(item => {
            let studentAll = [...studentGirlDataInfo.value, ...studentBoylDataInfo.value];
            console.log(studentAll);
            console.log(item);
            // eslint-disable-next-line max-nested-callbacks
            let ids = studentAll.map(v => v.id);
            if (ids.indexOf(item.id) === -1) {
              data.push({
                checked: false, // 选中状态
                disabled: false, // 是否禁选
                airBedNumber: item.airBedNumber,
                disableNumber: item.disableNumber,
                bedNum: item.bedNum,
                dormitoryId: item.dormitoryId,
                dormitoryName: item.dormitoryName,
                genderAttribute: item.genderAttribute,
                id: item.id,
                lou: item.storey,
                name: item.name,
                occupancyNumber: item.occupancyNumber,
                roomPhone: item.roomPhone,
                schoolId: item.schoolId,
                storey: item.storey,
                tenantId: item.tenantId,
                useState: item.useState,
                data: [],
                bedNumberList: []
              });
            } else {
              // eslint-disable-next-line max-nested-callbacks
              data = [...data, ...studentAll.filter(student => student.id === item.id)];
            }
          });
          data.forEach(v => {
            if (v.data.length) {
              v.checked = true;
            } else {
              v.checked = false;
            }
          });
          dormitoryListBoy.value[index].storeyList[key].roomList = data;
        });
      }
    }
  }
};

/** ****************************** 测试结束 ****************************************** */

let allocationDetailsGirl = ref([]); // 分配详情 女生
let allocationDetailsBoy = ref([]); // 分配详情 男生
let preAllocationGirlNum = ref(0); // 预分配人数 女生
let preAllocationBoyNum = ref(0); // 预分配人数 男生
let girlDataId = ref([]); // 选中班级 女士Id
let boyDataId = ref([]); // 选中班级 男生Id

// 宿舍分配弹窗
const dormitoryAllocation = reactive({
  title: '温馨提示',
  visible: false,
  btnState: '确定',
  width: '328px',
  state: 'normal',
  iconType: 'default'
});
const text = ref('');
// 精准分配弹窗
const dormitoryPrecise = reactive({
  title: '宿舍分配',
  visible: false,
  width: '889px',
  iconType: 'default',
  state: '保存'
});

const expandedKeys = ref([classId.value]); // 展开指定的树节点
const selectedKeys = ref([]); // 设置选中的树节点
const checkedKeys = ref([]); // 选中复选框的树节点
const treeData = ref([]);
let allocationDetailsList = ref([]); // 宿舍分配详情list
let genderValue = ref(0); // 女生
const searchValueGirl = ref(); // 搜索内容
const searchValue = ref(); // 搜索内容
const girlArr = ref([]); // 选中 女生人数 数组
const girlsNum = ref(0); // 选中 女生总人数
const boyArr = ref([]); // 选中 男生人数 数组
const boysNum = ref(0); // 选中 男生总人数
// 监听searchValue 如果为空 重新掉接口
// watch(searchValueGirl, (newValue, old) => {
//   if (!newValue) {
//     getDormitoryList(0);
//   }
// });
// watch(searchValue, (newValue, old) => {
//   if (!newValue) {
//     getDormitoryList(1);
//   }
// });

// 点击复选框触发
const checkTree = async (checkedKeys, e) => {
  searchValue.value = '';
  searchValueGirl.value = '';
  openKeys.value = [];
  dormitoryListGirl.value = JSON.parse(JSON.stringify(girlRoomList.value));
  dormitoryListBoy.value = JSON.parse(JSON.stringify(boyRoomList.value));
  // await getDormitoryList(0);
  // await getDormitoryList(1);
  console.log('多选');
  if (!e.checked) {
    // // 女生分配信息
    // studentGirlDataInfo.value = [];
    // // 男生分配信息
    // studentBoylDataInfo.value = [];

    console.log(e, 'e');
    console.log(allocationDetailsList.value, 'allocationDetailsList.value');

    if (e.node.childrenClass) {
      let classId = e.node.childrenClass.map(x => x.id);
      let arrList = [];
      let newArr = [];
      allocationDetailsList.value.forEach(x => {
        if (classId.indexOf(x.id) !== -1) arrList.push(x);
        if (classId.indexOf(x.id) === -1) newArr.push(x);
      });
      console.log(arrList, 'arrList');
      console.log(newArr, 'newArr');
      arrList.forEach(item => {
        item.list.forEach(elem => {
          if (elem.gender === '女' && elem.data.length) {
            let studentIdList = elem.distribution.map(x => x.studentId);
            console.log(dormitoryListGirl.value, 'dormitoryListGirl.value');
            console.log(studentIdList, 'dormitoryListGirl.value');
            elem.data.forEach(k => {
              // let dormitoryGirl = dormitoryListGirl.value
              //   // eslint-disable-next-line max-nested-callbacks
              //   .filter(x => x.id === k.dormitoryId)[0]
              //   // eslint-disable-next-line max-nested-callbacks
              //   .storeyList.filter(x => x.id === k.storey)[0]
              //   // eslint-disable-next-line max-nested-callbacks
              //   .roomList.filter(x => x.id === k.id)[0];

              let dormitoryGirl = studentGirlDataInfo.value.filter(
                // eslint-disable-next-line max-nested-callbacks
                x => x.dormitoryId === k.dormitoryId && x.storey === k.storey && x.id === k.id
              )[0];

              // eslint-disable-next-line max-nested-callbacks
              let newList = [];
              // eslint-disable-next-line max-nested-callbacks
              dormitoryGirl.data.forEach(v => {
                studentIdList.indexOf(v.studentId) === -1 && newList.push(v);
              });
              dormitoryGirl.data = newList;
              // dormitoryGirl.airBedNumber =
              //   dormitoryGirl.bedNumberList.length - dormitoryGirl.data.length;
              dormitoryGirl.occupancyNumber = dormitoryGirl.data.length;
              dormitoryGirl.airBedNumber =
                dormitoryGirl.bedNum - dormitoryGirl.occupancyNumber - dormitoryGirl.disableNumber;

              // eslint-disable-next-line max-nested-callbacks
              // studentGirlDataInfo.value.forEach(v => {
              //   if (v.id === dormitoryGirl.id) v = dormitoryGirl;
              // });
              // studentGirlDataInfo.value.push(dormitoryGirl);
            });
          }
          if (elem.gender === '男' && elem.data.length) {
            let studentIdList = elem.distribution.map(x => x.studentId);
            elem.data.forEach(k => {
              // let dormitoryBoy = dormitoryListBoy.value
              //   // eslint-disable-next-line max-nested-callbacks
              //   .filter(x => x.id === k.dormitoryId)[0]
              //   // eslint-disable-next-line max-nested-callbacks
              //   .storeyList.filter(x => x.id === k.storey)[0]
              //   // eslint-disable-next-line max-nested-callbacks
              //   .roomList.filter(x => x.id === k.id)[0];
              console.log(studentBoylDataInfo.value);
              let dormitoryBoy = studentBoylDataInfo.value.filter(
                // eslint-disable-next-line max-nested-callbacks
                x => x.dormitoryId === k.dormitoryId && x.storey === k.storey && x.id === k.id
              )[0];
              console.log(dormitoryBoy);
              console.log(dormitoryBoy.data);
              let newList = [];
              // eslint-disable-next-line max-nested-callbacks
              dormitoryBoy.data.forEach(v => {
                studentIdList.indexOf(v.studentId) === -1 && newList.push(v);
              });
              dormitoryBoy.data = newList;
              // dormitoryBoy.airBedNumber =
              //   dormitoryBoy.bedNumberList.length - dormitoryBoy.data.length;
              dormitoryBoy.occupancyNumber = dormitoryBoy.data.length;
              dormitoryBoy.airBedNumber =
                dormitoryBoy.bedNum - dormitoryBoy.occupancyNumber - dormitoryBoy.disableNumber;

              // studentBoylDataInfo.value.push(dormitoryBoy);
            });
          }
        });
      });
      let girl = [];
      let boy = [];

      sexChoice.value[0].data.forEach(item => {
        if (classId.indexOf(item.classId) === -1) girl.push(item);
      });
      sexChoice.value[0].data = girl;
      sexChoice.value[1].data.forEach(item => {
        if (classId.indexOf(item.classId) === -1) boy.push(item);
      });
      sexChoice.value[1].data = boy;
      allocationDetailsList.value = newArr;
    } else {
      let arr = allocationDetailsList.value.filter(elem => elem.id === e.node.id)[0];
      console.log(arr);
      console.log(studentBoylDataInfo.value);
      arr.list.forEach(elem => {
        if (elem.gender === '女' && elem.data.length) {
          let studentIdList = elem.distribution.map(x => x.studentId);
          elem.data.forEach(k => {
            // let dormitoryGirl = dormitoryListGirl.value
            //   .filter(x => x.id === k.dormitoryId)[0]
            //   .storeyList.filter(x => x.id === k.storey)[0]
            //   .roomList.filter(x => x.id === k.id)[0];

            let dormitoryGirl = studentGirlDataInfo.value.filter(
              // eslint-disable-next-line max-nested-callbacks
              x => x.dormitoryId === k.dormitoryId && x.storey === k.storey && x.id === k.id
            )[0];

            console.log(dormitoryGirl);
            let newList = [];
            dormitoryGirl.data.forEach(v => {
              studentIdList.indexOf(v.studentId) === -1 && newList.push(v);
            });
            dormitoryGirl.data = newList;
            // dormitoryGirl.airBedNumber =
            //   dormitoryGirl.bedNumberList.length - dormitoryGirl.data.length;

            dormitoryGirl.occupancyNumber = dormitoryGirl.data.length;
            dormitoryGirl.airBedNumber =
              dormitoryGirl.bedNum - dormitoryGirl.occupancyNumber - dormitoryGirl.disableNumber;

            // studentGirlDataInfo.value.push(dormitoryGirl);
          });
        }
        if (elem.gender === '男' && elem.data.length) {
          let studentIdList = elem.distribution.map(x => x.studentId);
          elem.data.forEach(k => {
            // let dormitoryBoy = dormitoryListBoy.value
            //   .filter(x => x.id === k.dormitoryId)[0]
            //   .storeyList.filter(x => x.id === k.storey)[0]
            //   .roomList.filter(x => x.id === k.id)[0];

            let dormitoryBoy = studentBoylDataInfo.value.filter(
              // eslint-disable-next-line max-nested-callbacks
              x => x.dormitoryId === k.dormitoryId && x.storey === k.storey && x.id === k.id
            )[0];

            console.log(dormitoryBoy);
            let newList = [];
            dormitoryBoy.data.forEach(v => {
              studentIdList.indexOf(v.studentId) === -1 && newList.push(v);
            });
            dormitoryBoy.data = newList;
            // dormitoryBoy.airBedNumber =
            //   dormitoryBoy.bedNumberList.length - dormitoryBoy.data.length;
            dormitoryBoy.occupancyNumber = dormitoryBoy.data.length;
            dormitoryBoy.airBedNumber =
              dormitoryBoy.bedNum - dormitoryBoy.occupancyNumber - dormitoryBoy.disableNumber;

            // studentBoylDataInfo.value.push(dormitoryBoy);
          });
        }
      });
      sexChoice.value[0].data = sexChoice.value[0].data.filter(v => v.classId !== e.node.id);
      sexChoice.value[1].data = sexChoice.value[1].data.filter(v => v.classId !== e.node.id);
      allocationDetailsList.value = allocationDetailsList.value.filter(x => x.id !== e.node.id);
    }

    // dormitoryListGirl.value.forEach(v => {
    //   v?.storeyList.forEach(k => {
    //     k?.roomList.forEach(value => {
    //       if (!value.data.length) value.checked = false;
    //     });
    //   });
    // });
    // dormitoryListBoy.value.forEach(v => {
    //   v?.storeyList.forEach(k => {
    //     k?.roomList.forEach(value => {
    //       if (!value.data.length) value.checked = false;
    //     });
    //   });
    // });
  } else {
    console.log('sjbwyaaa', e.node);
    if (e.node.childrenClass) {
      console.log('多选');
      let id = e.node.childrenClass.map(x => x.id);
      allocationDetailsListData(id);
    } else {
      console.log('单选');
      allocationDetailsListData([e.node.id]);
    }
  }
  studentGirlDataInfo.value = studentGirlDataInfo.value.filter(v => v.data.length);
  studentBoylDataInfo.value = studentBoylDataInfo.value.filter(v => v.data.length);
};

const allocationDetailsListData = arr => {
  console.log('wcnmlgb', arr);
  let list = [];
  treeData.value.forEach(ks => {
    ks.childrenClass.forEach(k => {
      k.childrenClass.forEach(v => {
        v.sectionName = ks.sectionName;
        if (arr.indexOf(v.id) !== -1) list.push(v);
      });
    });
  });
  list.forEach(x => {
    allocationDetailsList.value.push({
      className: x.sectionName + x.gradeName + x.className,
      key: x.key,
      id: x.id,
      list: [
        {
          gender: '女',
          distribution: [],
          noDistribution: [],
          data: [] // 选择分配的宿舍
        },
        {
          gender: '男',
          distribution: [],
          noDistribution: [],
          data: [] // 选择分配的宿舍
        }
      ]
    });
  });
  arr.forEach(async x => {
    // getStudentDistributionList 新的
    // getUnAllocationClassStudentId 旧的 x
    await getStudentDistributionList(JSON.parse(route.query.studentUserId)).then(res => {
      let data = res.data.data;
      console.log(data);
      data.forEach((item, index) => {
        // eslint-disable-next-line max-nested-callbacks
        let arrList = allocationDetailsList.value.filter(v => v.id === x)[0];
        if (item.gender === '女') {
          console.log(arrList);
          arrList.list[0].noDistribution = [...arrList.list[0].noDistribution, ...item.studentList];
          sexChoice.value[0].data = [...sexChoice.value[0].data, ...item.studentList];
        } else {
          arrList.list[1].noDistribution = [...arrList.list[1].noDistribution, ...item.studentList];
          sexChoice.value[1].data = [...sexChoice.value[1].data, ...item.studentList];
        }
      });
    });
  });
  console.log(allocationDetailsList.value);
};

let girlIdList = ref([]); // 选中班级女生的id 名字
let boylIdList = ref([]); // 选中班级男生的id 名字
let initialGirl = ref([]);
let initialBoy = ref([]);
const treeDatass = reactive([]);

function getAllocationDetails(data, sexChoiceGirl, sexChoiceBoy) {
  let allocationDetails = [];
  data.forEach(itemSection => {
    itemSection.childrenClass.forEach(item => {
      /*eslint-disable */
      item.childrenClass.forEach((items, i) => {
        let data = sexChoiceGirl.filter(elem => items.id === elem.classId);
        let girlData = [];
        data.forEach(i => {
          girlData.push({
            studentName: i.studentName,
            studentId: i.studentId,
            classId: i.classId
          });
        });
        let dataBoy = sexChoiceBoy.filter(elem => items.id === elem.classId);
        let boyData = [];
        dataBoy.forEach(i => {
          boyData.push({
            studentName: i.studentName,
            studentId: i.studentId,
            classId: i.classId
          });
        });
        /*eslint -enable */
        allocationDetails.push({
          className: itemSection.sectionName + items.gradeName + items.className,
          key: items.key,
          id: items.id,
          list: [
            {
              gender: '女',
              distribution: [],
              noDistribution: girlData,
              data: [] // 选择分配的宿舍
              // data: sexChoice[0].data
            },
            {
              gender: '男',
              distribution: [],
              noDistribution: boyData,
              // data: sexChoice[1].data
              data: []
            }
          ]
        });
      });
    });
  });

  allocationDetailsList.value = allocationDetails;
  console.log('分配详情的数组是什么', allocationDetailsList);
}

// ------------------宿舍列表------------------
let dormitoryListGirl = ref([]); // 女生
let dormitoryListBoy = ref([]); // 男生

const girlRoomList = ref([]);
const boyRoomList = ref([]);
// 获取宿舍列表
async function getDormitoryList(sex) {
  await getDormitorySexList(sex).then(res => {
    openKeys.value = [];
    if (sex === 0) {
      dormitoryListGirl.value = res.data.data;
      dormitoryListGirl.value.forEach(elem => {
        let storeyList = [];
        for (let i = 0; i < elem.totalStorey; i++) {
          let obj = {
            id: i + 1,
            roomList: []
          };
          storeyList.push(obj);
        }
        elem.storeyList = storeyList;
      });
      girlRoomList.value = JSON.parse(JSON.stringify(dormitoryListGirl.value));
    } else {
      dormitoryListBoy.value = res.data.data;
      dormitoryListBoy.value.forEach(elem => {
        let storeyList = [];
        for (let i = 0; i < elem.totalStorey; i++) {
          let obj = {
            id: i + 1,
            roomList: []
          };
          storeyList.push(obj);
        }
        elem.storeyList = storeyList;
      });
      boyRoomList.value = JSON.parse(JSON.stringify(dormitoryListBoy.value));
    }
    console.log('第三个执行的函数-getDormitoryList', dormitoryListBoy.value);
  });
  console.log('监听');
}
function onSearch(e, genderAttribute) {
  console.log(genderAttribute, 'genderAttribute');
  if (e) {
    getDormitoryRoomaNameList({ name: e || undefined, genderAttribute: genderAttribute }).then(
      res => {
        openKeys.value = [];

        let data = [];
        console.log(res.data.data, 'res.data.data');
        res.data.data.forEach(item => {
          let storeyList = [];
          let roomList = [];
          console.log(item.dormitoryRoomVOList, 'item.dormitoryRoomVOList');

          let iteStorey = null;
          item.dormitoryRoomVOList.forEach(ite => {
            let studentAll = [...studentGirlDataInfo.value, ...studentBoylDataInfo.value];
            console.log(studentAll);
            console.log(ite);
            // eslint-disable-next-line max-nested-callbacks
            let ids = studentAll.map(v => v.id);
            if (ids.indexOf(ite.id) === -1) {
              roomList.push(ite);
            } else {
              // eslint-disable-next-line max-nested-callbacks
              roomList = [...roomList, ...studentAll.filter(student => student.id === ite.id)];
            }
            iteStorey = ite.storey;
          });
          let obj = {
            id: iteStorey || 1,
            roomList: roomList
          };
          storeyList.push(obj);
          console.log(storeyList, 'storeyList');
          data.push({
            genderAttribute: item.genderAttribute,
            id: item.id,
            name: item.name,
            totalBed: item.totalBed,
            totalRoom: item.totalRoom,
            totalStorey: item.totalStorey,
            storeyList: storeyList
          });
        });
        console.log(genderValue.value, 'genderValue.value');
        if (Number(genderValue.value) === 0) {
          dormitoryListGirl.value = [];
          dormitoryListGirl.value = data;
          console.log(data, 'data-1');
          console.log(dormitoryListGirl.value, 'data-7');
          console.log('data-8', dormitoryListBoy.value);
        } else {
          dormitoryListBoy.value = [];
          dormitoryListBoy.value = data;
          console.log('data-9', dormitoryListBoy.value);
        }

        // isDormitoryShow(dormitoryListBoy.value);

        // let studentAll = [...studentGirlDataInfo.value, ...studentBoylDataInfo.value];
        // console.log(studentAll);
        // console.log(dormitoryListBoy.value);
        // studentAll.forEach(student => {
        //   // let studentList = data
        //   //   .filter(lou => lou.id === student.dormitoryId)[0]
        //   //   .storeyList.filter(ceng => ceng.id === student.storey)[0]
        //   //   .roomList.filter(fang => fang.id === student.roomId)[0];
        //   // if (studentList) studentList.checked === true;

        //   dormitoryListBoy.value.forEach(lou => {
        //     if (lou.id === student.dormitoryId) {
        //       // eslint-disable-next-line max-nested-callbacks
        //       lou.storeyList.forEach(ceng => {
        //         if (ceng.id === student.lou) {
        //           // eslint-disable-next-line max-nested-callbacks
        //           ceng.roomList.forEach(fang => {
        //             if (fang.id === student.id) {
        //               console.log(student);
        //               fang = student;
        //             }
        //             console.log(fang);
        //           });
        //           console.log(ceng);
        //         }
        //       });
        //     }
        //   });
        //   // if (student.id === item.id) {
        //   //   data.push(student);
        //   // } else {
        //   //   data.push({
        //   //     genderAttribute: item.genderAttribute,
        //   //     id: item.id,
        //   //     name: item.name,
        //   //     totalBed: item.totalBed,
        //   //     totalRoom: item.totalRoom,
        //   //     totalStorey: item.totalStorey,
        //   //     storeyList: storeyList
        //   //   });
        //   // }
        // });
      }
    );
  } else {
    getDormitoryList(Number(genderAttribute));
  }
}
// 女 要入参的数组
const checkboxGirlList = ref([]);
// 女生楼层checkbox Change事件
const checkboxChangeGirl = (data, checked) => {
  console.log(data, '555555555555');
  let bedNumberList = [];
  getRoomDetails(data.id).then(res => {
    res.data.data.forEach(item => {
      if (!item.studentUserId) {
        let obj = {
          bedId: item.id,
          bedNumber: item.bedNumber
        };
        bedNumberList.push(obj);
      }
    });
    data.bedNumberList = bedNumberList;
  });
  // 选中状态
  if (checked) {
    // 女生总数< = 房间人数
    if (sexChoice.value[0].data.length <= data.airBedNumber) {
      data.data = sexChoice.value[0].data;
      sexChoice.value[0].data = [];
    } else {
      // 女生总数> 房间人数
      data.data = sexChoice.value[0].data.slice(0, data.airBedNumber);
      sexChoice.value[0].data = sexChoice.value[0].data.slice(data.airBedNumber);
    }
    allocationDetailsList.value.forEach(item => {
      data.data.forEach(k => {
        if (k.classId === item.id) {
          item.list[0].data.push({
            id: data.id,
            name: data.name,
            dormitoryId: data.dormitoryId,
            storey: data.storey,
            lou: data.storey
          });

          item.list[0].distribution.push(k);
          let studentList = data.data.map(v => v.studentId);
          let noDistributionList = [];
          item.list[0].noDistribution.forEach(x => {
            if (studentList.indexOf(x.studentId) === -1) noDistributionList.push(x);
          });
          item.list[0].noDistribution = noDistributionList;
        }
      });
      item.list[0].data = deduplication(item.list[0].data);
    });
    data.occupancyNumber = Number(data.occupancyNumber) + data.data.length;
    data.airBedNumber = data.bedNum - data.occupancyNumber - data.disableNumber;

    studentGirlDataInfo.value.push(data);
  } else {
    data.occupancyNumber = Number(data.occupancyNumber) - data.data.length;
    data.airBedNumber = data.bedNum - data.occupancyNumber - data.disableNumber;
    // 取消选中
    if (sexChoice.value[0].data.length === 0) {
      sexChoice.value[0].data = data.data;
    } else {
      sexChoice.value[0].data = [...sexChoice.value[0].data, ...data.data];
    }
    allocationDetailsList.value.forEach(item => {
      item.list[0].data = item.list[0].data.filter(elem => data.id !== elem.id);
      let studentId = data.data.filter(elem => item.id === elem.classId).map(x => x.studentId);
      let student = data.data.filter(elem => item.id === elem.classId);
      let arr = [];
      item.list[0].distribution.forEach(k => {
        if (studentId.indexOf(k.studentId) === -1) arr.push(k);
      });
      item.list[0].distribution = arr;
      item.list[0].noDistribution = [...item.list[0].noDistribution, ...student];
    });

    let ids = studentGirlDataInfo.value.map(v => v.id);
    studentGirlDataInfo.value.splice(ids.indexOf(data.id), 1);
  }
  let dataList = [];
  let preAllocationData = [];
  dormitoryListGirl.value.forEach(item => {
    item.storeyList.forEach(ite => {
      ite.roomList.forEach(items => {
        if (sexChoice.value[0].num === 0) {
          if (!items.checked) {
            items.disabled = true;
          }
        } else {
          items.disabled = false;
        }
        if (items.checked) {
          console.log(items);
          dataList.push({
            id: items.id,
            name: items.name
          });
          preAllocationData.push(items.occupancyNumber);
        }
      });
    });
  });

  let reducer = (accumulator, currentValue) => accumulator + currentValue;
  preAllocationGirlNum.value = preAllocationData.length > 0 ? preAllocationData.reduce(reducer) : 0;
  allocationDetailsGirl.value = dataList;
  // console.log(allocationDetailsList.value);
  // 新加的逻辑开始
  if (checked) {
    let studentListArr = [];
    data.data.forEach(item => {
      studentListArr.push(item.studentId);
    });

    let objnew = {
      roomId: data.id,
      studentIdList: studentListArr
    };
    checkboxGirlList.value.push(objnew);
  } else {
    console.log('走取消选中了了吗');
    checkboxGirlList.value.forEach((item, index) => {
      if (item.roomId === data.id) {
        checkboxGirlList.value.splice(index, 1);
      }
    });
  }
  console.log('要入参的数据结构是什么', checkboxGirlList.value);
  // 新加的逻辑结束
  console.log(data);
};
// 男 数组
const checkboxBoyList = ref([]);
// 男生楼层checkbox Change事件 (room, 1, $event, index, key, i)
const checkboxChangeBoy = (data, checked) => {
  console.log('男僧data', data);
  console.log('男僧data.data', data.data);
  console.log('男僧checked', checked);
  console.log(checked);
  let bedNumberList = [];
  getRoomDetails(data.id).then(res => {
    res.data.data.forEach(item => {
      if (!item.studentUserId) {
        let obj = {
          bedId: item.id,
          bedNumber: item.bedNumber
        };
        bedNumberList.push(obj);
      }
    });
    data.bedNumberList = bedNumberList;
  });

  // 选中状态
  if (checked) {
    // 女生总数< = 房间人数
    if (sexChoice.value[1].data.length <= data.airBedNumber) {
      data.data = sexChoice.value[1].data;
      sexChoice.value[1].data = [];
    } else {
      // 女生总数> 房间人数
      data.data = sexChoice.value[1].data.slice(0, data.airBedNumber);
      sexChoice.value[1].data = sexChoice.value[1].data.slice(data.airBedNumber);
    }
    allocationDetailsList.value.forEach(item => {
      data.data.forEach(k => {
        if (k.classId === item.id) {
          item.list[1].data.push({
            id: data.id,
            name: data.name,
            dormitoryId: data.dormitoryId,
            storey: data.storey,
            lou: data.storey
          });

          item.list[1].distribution.push(k);
          let studentList = data.data.map(v => v.studentId);
          let noDistributionList = [];
          item.list[1].noDistribution.forEach(x => {
            if (studentList.indexOf(x.studentId) === -1) noDistributionList.push(x);
          });
          item.list[1].noDistribution = noDistributionList;
        }
      });
      item.list[1].data = deduplication(item.list[1].data);
    });
    data.occupancyNumber = Number(data.occupancyNumber) + data.data.length;
    data.airBedNumber = data.bedNum - data.occupancyNumber - data.disableNumber;

    studentBoylDataInfo.value.push(data);
  } else {
    data.occupancyNumber = Number(data.occupancyNumber) - data.data.length;
    data.airBedNumber = data.bedNum - data.occupancyNumber - data.disableNumber;
    // 取消选中
    if (sexChoice.value[1].data.length === 0) {
      sexChoice.value[1].data = data.data;
    } else {
      sexChoice.value[1].data = [...sexChoice.value[1].data, ...data.data];
    }
    allocationDetailsList.value.forEach(item => {
      item.list[1].data = item.list[1].data.filter(elem => data.id !== elem.id);
      let studentId = data.data.filter(elem => item.id === elem.classId).map(x => x.studentId);
      let student = data.data.filter(elem => item.id === elem.classId);
      let arr = [];
      item.list[1].distribution.forEach(k => {
        console.log(k.studentId);
        console.log(studentId);
        if (studentId.indexOf(k.studentId) === -1) arr.push(k);
      });
      item.list[1].distribution = arr;
      item.list[1].noDistribution = [...item.list[1].noDistribution, ...student];
    });

    let ids = studentBoylDataInfo.value.map(v => v.id);
    studentBoylDataInfo.value.splice(ids.indexOf(data.id), 1);
  }
  let dataListBoy = [];
  let preAllocationDataBoy = [];
  dormitoryListBoy.value.forEach(item => {
    item.storeyList.forEach(ite => {
      ite.roomList.forEach(items => {
        if (sexChoice.value[1].num === 0) {
          if (!items.checked) {
            items.disabled = true;
          }
        } else {
          items.disabled = false;
        }
        if (items.checked) {
          dataListBoy.push({
            id: items.id,
            name: items.name
          });
          preAllocationDataBoy.push(items.occupancyNumber);
        }
      });
    });
  });
  let reducer = (accumulator, currentValue) => accumulator + currentValue;
  preAllocationBoyNum.value =
    preAllocationDataBoy.length > 0 ? preAllocationDataBoy.reduce(reducer) : 0;
  allocationDetailsBoy.value = dataListBoy;

  // 新加的逻辑开始
  if (checked) {
    let studentListArr = [];
    data.data.forEach(item => {
      studentListArr.push(item.studentId);
    });

    let objnew = {
      roomId: data.id,
      studentIdList: studentListArr
    };
    checkboxBoyList.value.push(objnew);
  } else {
    console.log('走取消选中了了吗');
    checkboxBoyList.value.forEach((item, index) => {
      if (item.roomId === data.id) {
        checkboxBoyList.value.splice(index, 1);
      }
    });
  }
  console.log('要入参的数据结构是什么', checkboxBoyList.value);
  // 新加的逻辑结束
};
// 保留数组中非重复数据
const deduplication = arr => {
  let idList = [...new Set(arr.map(x => x.id))];
  let arrList = [];
  idList.forEach(elem => {
    arrList.push(arr.find(x => x.id === elem));
  });
  return arrList;
};
const openKeys = ref([]);
function onOpenChange(e) {}
function tabClick(e) {
  console.log(e, 'tabs数据');
  genderValue.value = e;
}
// --------------------------------------------
// 精确分配
function preciseDistribution() {
  if (sexChoice.value[0].data.length !== 0 || sexChoice.value[1].data.length !== 0) {
    dormitoryAllocation.btnState = '我知道了';
    text.value = '未选择宿舍楼、房间范围，无法进行精确分配';
    // text.value = '当前包含未预分配房间的班级，无法进行精确分配';
    dormitoryAllocation.visible = true;
    return false;
  }
  let boyDatas = [];
  let girlDatas = [];
  let paramsData = [];
  let paramsDataBoy = [];
  let datassBoy = [];
  let dataGirl = [];
  dormitoryListGirl.value = JSON.parse(JSON.stringify(girlRoomList.value));
  dormitoryListBoy.value = JSON.parse(JSON.stringify(boyRoomList.value));
  console.log(studentGirlDataInfo.value);
  console.log(studentBoylDataInfo.value);
  console.log(dormitoryListGirl.value);
  console.log(dormitoryListBoy.value);
  studentGirlDataInfo.value.forEach(info => {
    dormitoryListGirl.value.forEach(lou => {
      lou.storeyList.forEach(ceng => {
        if (ceng.id === info.storey && lou.id === info.dormitoryId) {
          ceng.roomList.push(info);
        }
      });
    });
  });
  studentBoylDataInfo.value.forEach(info => {
    dormitoryListBoy.value.forEach(lou => {
      lou.storeyList.forEach(ceng => {
        if (ceng.id === info.storey && lou.id === info.dormitoryId) {
          ceng.roomList.push(info);
        }
      });
    });
  });

  dormitoryListGirl.value.forEach(item => {
    let ceng = [];
    item.storeyList.forEach(items => {
      let fang = [];
      items.roomList.forEach((ite, index) => {
        if (ite.checked) {
          let chuang = [];
          // eslint-disable-next-line max-nested-callbacks
          ite.bedNumberList.forEach(bedNums => {
            let obj = {
              title: bedNums.bedNumber,
              data: {},
              checked: false,
              louId: item.id,
              homeId: ite.id,
              bedId: bedNums.bedId,
              lowName: ite.dormitoryName,
              key: bedNums.bedNumber
            };
            chuang.push(obj);
          });
          paramsData.push({
            dormitory: item.name, // 楼
            dormitoryId: item.id, // 楼
            floor: items.id, // 楼层
            roomNum: ite.name, // 房间号
            roomId: ite.id, // 房间号
            attribute: '女生宿舍',
            bedInfo: [],
            distributionBedNum: ite.data.length // 分配床位数
          });
          let fangObj = {
            id: ite.id,
            title: ite.name,
            bedNum: ite.bedNum,
            occupancyNumber: ite.occupancyNumber,
            airBedNumber: ite.airBedNumber,
            disableNumber: ite.disableNumber,
            dormitoryId: ite.dormitoryId,
            key: String(item.id) + '-' + String(items.id) + '-' + String(index),
            children: chuang
          };
          fang.push(fangObj);
        }
      });
      let cengObj = {
        storey: items.id,
        lou: items.id,
        title: items.id + '楼',
        key: String(item.id) + '-' + String(items.id),
        children: fang
      };
      ceng.push(cengObj);
    });
    let louObj = {
      dormitoryId: item.id,
      title: item.name,
      key: String(item.id),
      children: ceng
    };
    dataGirl.push(louObj);
  });
  let boyDatass = [];

  dormitoryListBoy.value.forEach(item => {
    let cengBoy = [];
    item.storeyList.forEach(items => {
      let fangBoy = [];
      items.roomList.forEach((ite, index) => {
        if (ite.checked) {
          let chuangBoy = [];
          // eslint-disable-next-line max-nested-callbacks
          ite.bedNumberList.forEach(bedNums => {
            let objBoy = {
              title: bedNums.bedNumber,
              data: {},
              checked: false,
              louId: item.id,
              homeId: ite.id,
              bedId: bedNums.bedId,
              lowName: ite.dormitoryName,
              key: bedNums.bedNumber
            };
            chuangBoy.push(objBoy);
          });
          paramsDataBoy.push({
            dormitory: item.name, // 楼
            dormitoryId: item.id, // 楼
            floor: items.id, // 楼层
            roomNum: ite.name, // 房间号
            roomId: ite.id, // 房间号
            attribute: '男生宿舍',
            bedInfo: [],
            distributionBedNum: ite.data.length // 分配床位数
          });
          let fangBoyObj = {
            id: ite.id,
            title: ite.name,
            bedNum: ite.bedNum,
            occupancyNumber: ite.occupancyNumber,
            airBedNumber: ite.airBedNumber,
            disableNumber: ite.disableNumber,
            dormitoryId: ite.dormitoryId,
            key: String(item.id) + '-' + String(items.id) + '-' + String(index),
            children: chuangBoy
          };
          fangBoy.push(fangBoyObj);
        }
      });
      let cengBoyObj = {
        storey: items.id,
        lou: items.id,
        title: items.id + '楼',
        key: String(item.id) + '-' + String(items.id),
        children: fangBoy
      };
      cengBoy.push(cengBoyObj);
    });
    let louBoyObj = {
      dormitoryId: item.id,
      title: item.name,
      key: String(item.id),
      children: cengBoy
    };
    datassBoy.push(louBoyObj);
  });

  let tableData = paramsData.concat(paramsDataBoy);
  allocationDetailsList.value.forEach(item => {
    item.list[1].distribution.forEach(items => {
      boyDatas.push(items);
    });
    item.list[0].distribution.forEach(items => {
      girlDatas.push(items);
    });
  });

  let bb = [];
  console.log(treeData.value);
  treeData.value.forEach(itemGradle => {
    let cc = [];
    itemGradle.childrenClass.forEach(item => {
      let aa = [];
      item.childrenClass.forEach(items => {
        if (checkedKeys.value.indexOf(items.key) !== -1) {
          aa.push(items);
        }
      });
      cc.push({
        className: item.className,
        gradeId: item.gradeId,
        gradeName: item.gradeName,
        key: item.key,
        childrenClass: aa
      });
    });

    bb.push({
      sectionName: itemGradle.sectionName,
      sectionCode: itemGradle.sectionCode,
      gradeName: itemGradle.sectionName,
      key: itemGradle.key,
      childrenClass: cc
    });
  });
  let newDataGirl = [];
  dataGirl.forEach(v => {
    v.children = v.children.filter(x => x.children.length);
    if (v.children.length) newDataGirl.push(v);
  });
  dataGirl = newDataGirl;

  let newDataBoy = [];
  datassBoy.forEach(v => {
    v.children = v.children.filter(x => x.children.length);
    if (v.children.length) newDataBoy.push(v);
  });
  datassBoy = newDataBoy;

  console.log(girlDatas, 'dsdvsdv');
  console.log(datassBoy, 'dsdvsdv');
  if (sexChoice.value[0].data.length !== 0 || sexChoice.value[1].data.length !== 0) {
    dormitoryAllocation.btnState = '我知道了';
    text.value = '未选择宿舍楼、房间范围，无法进行精确分配';
    // text.value = '当前包含未预分配房间的班级，无法进行精确分配';
    dormitoryAllocation.visible = true;
  } else {
    datassBoy.forEach(l => {
      l.children.forEach(c => {
        c.children.forEach(f => {
          f.classList = [];
        });
      });
    });
    dataGirl.forEach(l => {
      l.children.forEach(c => {
        c.children.forEach(f => {
          f.classList = [];
        });
      });
    });
    tableData.forEach(v => {
      v.classList = [];
    });
    let tableDataGirl = tableData.filter(v => v.attribute === '女生宿舍');
    let tableDataBoy = tableData.filter(v => v.attribute === '男生宿舍');
    allocationDetailsList.value.forEach(v => {
      v.list.forEach(k => {
        if (k.gender === '女') {
          k.data.forEach(x => {
            dataGirl
              // eslint-disable-next-line max-nested-callbacks
              .filter(value => value.dormitoryId === x.dormitoryId)[0]
              // eslint-disable-next-line max-nested-callbacks
              .children.filter(value => value.storey === x.storey)[0]
              // eslint-disable-next-line max-nested-callbacks
              .children.filter(value => value.id === x.id)[0]
              .classList.push(v);
            // eslint-disable-next-line max-nested-callbacks
            tableDataGirl.forEach(item => {
              if (
                item.dormitoryId === x.dormitoryId &&
                item.floor === x.storey &&
                item.roomId === x.id
              ) {
                item.classList.push(v);
              }
            });
          });
        }
        if (k.gender === '男') {
          k.data.forEach(x => {
            datassBoy
              // eslint-disable-next-line max-nested-callbacks
              .filter(value => value.dormitoryId === x.dormitoryId)[0]
              // eslint-disable-next-line max-nested-callbacks
              .children.filter(value => value.storey === x.storey)[0]
              // eslint-disable-next-line max-nested-callbacks
              .children.filter(value => value.id === x.id)[0]
              .classList.push(v);
            // eslint-disable-next-line max-nested-callbacks
            tableDataBoy.forEach(item => {
              if (
                item.dormitoryId === x.dormitoryId &&
                item.floor === x.storey &&
                item.roomId === x.id
              ) {
                item.classList.push(v);
              }
            });
          });
        }
      });
    });
    let obj = {
      assignedNum: 0, // 分配人数
      treeDataListBoy: datassBoy, // 选中男生的宿舍结构
      treeDataListGirl: dataGirl, // 选中的女生的宿舍结构
      expandedKeys: checkedKeys.value,
      noAssigned: girlDatas.concat(boyDatas).length, // 未分配人数
      boyData: boyDatas, // 选中分配男生数据
      girlData: girlDatas, // 选中分配女生数据
      treeData: bb, // 班级树
      tableData: JSON.stringify(tableData), // 宿舍参数
      expandedKeysNow: expandedKeys.value
    };
    console.log(obj);
    localStorage.setItem('STUDENT_DISTRIBUTION', JSON.stringify(obj));
    router.push({
      path: '/admin/classInfo/classInfoDeta'
    });
    console.log(checkedKeys.value);
  }
}

// 一件分配
function goDistribution() {
  console.log(sexChoice.value[0].data.length, '女生总数');
  console.log(sexChoice.value[1].data.length, '男生总数');
  // if (preAllocationGirlNum.value === 0 || preAllocationBoyNum.value === 0) {
  //   dormitoryAllocation.btnState = '我知道了';
  //   text.value = '所选内容包含未预分配房间的班级，无法进行一键分配';
  //   dormitoryAllocation.visible = true;
  // }
  if (sexChoice.value[0].data.length !== 0 || sexChoice.value[1].data.length !== 0) {
    dormitoryAllocation.btnState = '我知道了';
    text.value = '未选择宿舍楼、房间范围，无法进行一键分配';
    // text.value = '所选内容包含未预分配房间的班级，无法进行一键分配';
    dormitoryAllocation.visible = true;
  } else if (checkedKeys.value.length === 1) {
    dormitoryAllocation.btnState = '确定';
    dormitoryAllocation.state = '一键分配';
    text.value = '将在所选范围内为该班级一键分配';
    dormitoryAllocation.visible = true;
  } else {
    dormitoryAllocation.btnState = '确定';
    dormitoryAllocation.state = '一键分配';
    text.value = '将在所选范围内为所选班级一键分配';
    dormitoryAllocation.visible = true;
  }
}
// 一键分配
const toDistribution = debounce(function () {
  let roomIdGirl = [];
  let roomIdBoy = [];
  let girlData = [];
  let boyData = [];
  allocationDetailsList.value.forEach(item => {
    console.log(item, 'ssscfdfhusy');
    console.log(item.list[0].distribution, 'ssscfdfhusy222222');
    item.list[0].data.forEach(items => {
      roomIdGirl.push(items.id);
    });
    item.list[1].data.forEach(items => {
      roomIdBoy.push(items.id);
    });

    item.list[0].distribution.forEach(item0 => {
      console.log(item0, 'item0');
      girlData.push(item0.studentId);
    });
    console.log(girlData, 'girlData');
    item.list[1].distribution.forEach(item1 => {
      boyData.push(item1.studentId);
    });
  });
  let params = {
    schoolboy: {
      studentIdList: boyData,
      roomIdList: roomIdBoy
    },
    schoolgirl: {
      studentIdList: girlData,
      roomIdList: roomIdGirl
    }
  };
  console.log('宿舍分配入参', params);

  let paramsNew = {
    schoolboyList: checkboxBoyList.value,
    schoolgirlList: checkboxGirlList.value
  };
  btnLoading.value = true;
  automaticAssignDormitory(paramsNew).then(res => {
    if (res.data.code === 200) {
      Message.success('分配成功');
      // router.push('/admin/classInfo');
      router.push('/admin/usersInfo');
      dormitoryPrecise.visible = false;
      dormitoryAllocation.visible = false;
      btnLoading.value = false;
    } else {
      Message.error(res.data.msg);
      dormitoryPrecise.visible = false;
      dormitoryAllocation.visible = false;
      btnLoading.value = false;
    }
  });
}, 500);
function handleOk() {
  text.value = '有未分配的信息，是否确认保存？';
  dormitoryAllocation.visible = true;
}
function handleCancel() {
  text.value = '关闭后将取消所选设置，是否确认关闭？？';
  btnLoading.value = false;
  dormitoryAllocation.visible = true;
}
function dormitoryTip(state) {
  if (state === '一键分配') {
    toDistribution(); // 分配
  } else {
    dormitoryPrecise.visible = false;
    dormitoryAllocation.visible = false;
    btnLoading.value = false;
  }
}
function dormitoryCancel() {
  dormitoryAllocation.visible = false;
  btnLoading.value = false;
}
</script>

<style lang="less" scoped>
.checkBox {
  padding-right: 119px;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  li {
    line-height: 25px;
    width: 50%;
  }
}
.box {
  background: #f2f2f2;
  // padding: 50px 120px 24px;
  // height: 100vh;
  min-height: 100vh;
  min-width: 1300px;
  .box-content {
    background: #ffffff;
    border-radius: 4px;
    padding: 24px;
    .no-accurate {
      cursor: no-drop;
      background: #e6e6e6;
      padding: 5px 16px;
      color: #ffffff;
      border-radius: 4px;
      font-size: 14px;
    }
    .no-accurate-left {
      margin-left: 16px;
    }
    .bottom-content {
      display: flex;
      justify-content: space-between;
      margin-top: 24px;
      .bottom-content-left {
        // width: 208px;
        width: 20%;
        border: 1px solid #e1dddd;
        border-radius: 4px;
        padding: 16px 10px;
      }
      .bottom-content-center {
        // width: 555px;
        width: 48%;
        border: 1px solid #e1dddd;
        border-radius: 4px;
        padding-bottom: 10px;
      }
      .bottom-content-right {
        max-height: 706px;
        overflow: auto;
        .allocation-details-title {
          font-size: 16px;
          font-family: Source Han Sans CN, Source Han Sans CN-Regular;
          font-weight: 400;
          color: #222222;
          margin-bottom: 21.5px;
        }
        .class-name {
          margin-bottom: 11px;
          font-size: 14px;
          font-family: Source Han Sans CN, Source Han Sans CN-Regular;
          font-weight: 400;
          color: #222222;
        }
        // width: 341px;
        width: 30%;
        border: 1px solid #e1dddd;
        border-radius: 4px;
        padding: 24px;
        .info {
          margin-bottom: 16px;
          padding: 0 16px;
          height: 32px;
          background: #f8f8f8;
          border-radius: 4px;
          display: flex;
          justify-content: space-between;
          p {
            font-size: 16px;
            line-height: 32px;
            font-family: Source Han Sans CN, Source Han Sans CN-Regular;
            font-weight: 400;
            // color: #666666;
          }
        }
        .info-content {
          display: flex;
          // justify-content: space-between;
          align-items: center;
          flex-wrap: wrap;
          .details {
            margin-bottom: 17px;
            margin-right: 8px;
          }
          div {
            // width: 48px;
            // height: 24px;
            padding: 1px 6px;
            // line-height: 24px;
            background: #fdf4ec;
            border-radius: 4px;
            font-size: 14px;
            font-family: Source Han Sans CN, Source Han Sans CN-Regular;
            font-weight: 400;
            text-align: center;
            color: @color-test;
          }
        }
      }
    }
  }
}
.campus {
  width: 64px;
  height: 24px;
  font-size: 16px;
  font-family: Source Han Sans CN, Source Han Sans CN-Regular;
  font-weight: 400;
  text-align: LEFT;
  color: #222222;
  line-height: 24px;
  margin-bottom: 16px;
}
.content {
  display: flex;
  justify-content: space-between;
  .option {
    width: 208px;
    border: 1px solid #e1dddd;
    border-radius: 4px;
  }
  .details {
    width: 480px;
    border: 1px solid #e1dddd;
    border-radius: 4px;
    .info {
      height: 46px;
      font-size: 16px;
      line-height: 46px;
      font-family: Source Han Sans CN, Source Han Sans CN-Regular;
      font-weight: 400;
      color: #222222;
      border-bottom: 1px solid #e1dddd;
      padding-left: 16px;
    }
    .info-content {
      height: 32px;
      display: flex;
      align-items: center;
      padding: 24px 24px;
    }
  }
  .detailsStudent {
    width: 622px;
    border: 1px solid #e1dddd;
    border-radius: 4px;
    .info {
      height: 46px;
      font-size: 16px;
      line-height: 46px;
      font-family: Source Han Sans CN, Source Han Sans CN-Regular;
      font-weight: 400;
      color: #222222;
      border-bottom: 1px solid #e1dddd;
      padding-left: 16px;
    }
    .info-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24px;
    }
  }
}
.checkOutStyle {
  width: 280px;
  height: 72px;
  background: #f8f8f8;
  border-radius: 4px;
  display: flex;
  align-items: center;
  padding: 14px;
  img {
    margin-right: 8px;
  }
}

.micro-dormitory-radio-wrapper {
  display: flex !important;
  height: 30px !important;
  line-height: 0 !important;
  align-items: center !important;
}
/deep/.micro-dormitory-tabs-nav {
  padding: 0 10px !important;
}
.micro-dormitory-tabs-tabpane {
  margin-left: 10px !important;
}

.micro-dormitory-tabs-tab-btn {
  font-size: 16px !important;
}

&::-webkit-scrollbar {
  width: 6px;
}

&::-webkit-scrollbar-thumb {
  background: rgba(20, 20, 20, 0.2);
  border-radius: 3px;
}

&::-webkit-scrollbar-track {
  background: transparent;
}
// .micro-dormitory-checkbox-wrapper-checked.deta-checked {
// }
// .room-box-checked {
//   background: var(--van-primary-color-web);
// }
</style>
